package site.isscloud.project.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import site.isscloud.project.domain.vo.BuildingEventVo;
import site.isscloud.project.domain.PjAlarmEvent;
import site.isscloud.project.mapper.PjBuildingEventMapper;
import site.isscloud.project.service.IPjBuildingEventService;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 楼栋告警Service业务层处理
 */
@Service
public class PjBuildingEventServiceImpl implements IPjBuildingEventService {

    @Autowired
    private PjBuildingEventMapper pjBuildingEventMapper;

    /**
     * 查询楼栋告警汇总列表
     */
    @Override
    public List<BuildingEventVo> selectBuildingEventList(BuildingEventVo buildingEventVo) {
        return pjBuildingEventMapper.selectBuildingEventList(buildingEventVo);
    }

    /**
     * 根据位置ID查询对应的告警事件详情
     */
    @Override
    public List<PjAlarmEvent> selectEventDetailsByLocation(Long locationId, String deviceNo, Integer chanel,
                                                           String beginTime, String endTime, Integer eventStatus) {
        // 根据locationId获取位置信息
        BuildingEventVo locationInfo = pjBuildingEventMapper.selectLocationInfoById(locationId);
        if (locationInfo == null) {
            return new ArrayList<>();
        }

        // 转换时间格式
        Date beginDate = parseDate(beginTime);
        Date endDate = parseDate(endTime);

        return pjBuildingEventMapper.selectEventDetailsByLocation(
                locationInfo.getMarkerStart(),
                locationInfo.getMarkerEnd(),
                deviceNo,
                chanel,
                beginDate,
                endDate,
                eventStatus);
    }

    /**
     * 字符串转Date
     */
    private Date parseDate(String dateStr) {
        if (dateStr == null || dateStr.trim().isEmpty()) {
            return null;
        }
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            return sdf.parse(dateStr);
        } catch (ParseException e) {
            try {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                return sdf.parse(dateStr);
            } catch (ParseException ex) {
                return null;
            }
        }
    }
}